//
//  TodayHomeViewController.m
//  TourPlay
//
//  Created by dllo on 15/11/17.
//  Copyright © 2015年 王军岐. All rights reserved.
//

#import "TodayHomeViewController.h"
#import "TodayHomeCell.h"
#import "TodayHomeMoreCell.h"
#import "ActivitieDetailsViewController.h"
#import "ToDaySubViewController.h"
#import "UINavigationController+FDFullscreenPopGesture.h"

@interface TodayHomeViewController () <UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, UINavigationControllerDelegate, WJQAlertView>

@property (nonatomic, retain) UITableView *myTableV;
@property (nonatomic, retain) NSMutableDictionary *toDayDic;
@property (nonatomic, retain) NSMutableArray *sortSectionArr;
@property (nonatomic, retain) UILabel *timeLabel;

@property (nonatomic, assign) NSInteger timeHour;
@property (nonatomic, assign) NSInteger timeMinute;

@property (nonatomic, retain) WJQAlertView *aler;
@property (nonatomic, retain) UIImageView *timeBackImageV; // 时间标题背景

@end

@implementation TodayHomeViewController
- (void)dealloc
{
    [_myTableV release];
    [_toDayDic release];
    [_sortSectionArr release];
    [_timeLabel release];
    [_aler release];
    [_timeBackImageV release];
    [super dealloc];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.delegate navigationViewWithIsHidden:NO];
    self.navigationController.fd_prefersNavigationBarHidden = YES;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        self.navigationController.delegate = self;
    }
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        self.navigationController.delegate = nil;
    }
}
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    id<UIViewControllerTransitionCoordinator> tc = navigationController.topViewController.transitionCoordinator;
    [tc notifyWhenInteractionEndsUsingBlock:^(id<UIViewControllerTransitionCoordinatorContext> context) {
        NSLog(@"7: %i", [context isCancelled]);
        if (0 == [context isCancelled]) {
            [self.delegate navigationViewWithIsHidden:NO];
        }
        
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor clearColor];
    self.toDayDic = [NSMutableDictionary dictionary];
    self.sortSectionArr = [NSMutableArray array];
    self.timeMinute = 0;
    
    
    // 划线
    UIView *viewBack = [[UIView alloc] initWithFrame:CGRectMake(17, 0, 1, self.view.frame.size.height)];
    [self.view addSubview:viewBack];
    [viewBack release];
    
    [self addColorChangedBlock:^{
        
        viewBack.nightBackgroundColor = [ColorSingleton shareSingleton].cellColor;
        viewBack.normalBackgroundColor = [UIColor colorWithRed:0.88 green:0.87 blue:0.88 alpha:1];
    }];
    
    
    self.myTableV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49) style:UITableViewStylePlain];
    self.myTableV.backgroundColor = [UIColor clearColor];
    self.myTableV.dataSource = self;
    self.myTableV.delegate = self;
    // 取消分割线
    self.myTableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.myTableV registerClass:[TodayHomeCell class] forCellReuseIdentifier:@"cell"];
    [self.myTableV registerClass:[TodayHomeMoreCell class] forCellReuseIdentifier:@"cellMore"];
    [self.view addSubview:self.myTableV];
    [_myTableV release];
    
    [self addHeaderRefresh];
    
    // 接收城市改变通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(homeRefurbish:) name:@"homeRefurbish" object:nil];
}
#pragma mark - 城市改变通知
- (void)homeRefurbish:(NSNotification *)sender
{
    // 马上进入刷新状态
    [self.myTableV.header beginRefreshing];
}
#pragma mark - 下拉刷新
-(void)addHeaderRefresh
{
    self.myTableV.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        NSLog(@"下拉刷新");

        [self getUpdate];
    }];
    // 马上进入刷新状态
    [self.myTableV.header beginRefreshing];
}
#pragma mark - scrollView滑动相关
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//    NSInteger time = (NSInteger)floor(self.myTableV.contentOffset.y) % 60;
//    if (time >= 0) {
//
//        self.timeMinute = time;
////        NSLog(@"%ld", (NSInteger)floor(self.myTableV.contentOffset.y) % 60);
//        self.timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld", self.timeHour, self.timeMinute];
//    }
}
#pragma mark - 表格
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
//    NSLog(@"section : %ld", section);
    self.timeHour = [[self.sortSectionArr objectAtIndex:section] intValue];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
    view.backgroundColor = [UIColor clearColor];
    
    self.timeBackImageV = [[UIImageView alloc] initWithFrame:CGRectMake(5, 25 / 2.f, 78, 25)];
    self.timeBackImageV.userInteractionEnabled = YES;
    self.timeBackImageV.tag = section;
    
    
    if (self.timeHour < 6) {
        self.timeBackImageV.image = [UIImage imageNamed:@"today_time_0@2x.png"];
    } else if (self.timeHour < 12) {
        self.timeBackImageV.image = [UIImage imageNamed:@"today_time_6@2x.png"];
    } else if (self.timeHour < 18) {
        self.timeBackImageV.image = [UIImage imageNamed:@"today_time_12@2x.png"];
    } else {
        self.timeBackImageV.image = [UIImage imageNamed:@"today_time_18@2x.png"];
    }
    [view addSubview:self.timeBackImageV];
    [_timeBackImageV release];
    
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(25, 2.5, 40, 20)];
//    self.timeLabel.backgroundColor = [UIColor brownColor];
    self.timeLabel.textColor = [UIColor colorWithRed:0.99 green:0.95 blue:0.88 alpha:1];
    self.timeLabel.font = [UIFont systemFontOfSize:13.5f];
    self.timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld", self.timeHour, self.timeMinute];
    [self.timeBackImageV addSubview:self.timeLabel];
    [_timeLabel release];
    
    
    // 小三角符号
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(self.timeLabel.frame.origin.x + self.timeLabel.frame.size.width, 10, 8, 5)];
    imageV.image = [UIImage imageNamed:@"index_sanjiao@2x.png"];
    [self.timeBackImageV addSubview:imageV];
    [imageV release];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.timeBackImageV addGestureRecognizer:tap];
    [tap release];
    
    return view;
}
- (void)tapAction:(UITapGestureRecognizer *)sender
{
    
    
    UIImageView *imageV = (UIImageView *)sender.view;
    
    self.aler = [WJQAlertView wjqAlertViewWithTitle:@"选择时间"];
    self.aler.delegate = self;
    
    NSMutableArray *arr = [NSMutableArray array];
    for (NSString *str in self.sortSectionArr) {
        [arr addObject:[NSString stringWithFormat:@"%02d:00", [str intValue]]];
    }
    self.aler.listArray = [NSMutableArray arrayWithArray:arr];
    [self.aler setListViewWithArray:arr Row:imageV.tag];

}
- (void)goToRowWithIndexPath:(NSIndexPath *)indexPath
{
//    NSLog(@"indexPath : section %ld", indexPath.row);
//    + (instancetype)indexPathForRow:(NSInteger)row inSection:(NSInteger)section;
    NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:indexPath.row];
    [self.myTableV scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionTop animated:YES];
    [self.aler Hidden];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row > 4) {
        return 45 * AUTOSCREEN_HEIGHT;
    }
    return (SCREEN_HEIGHT - 50 - 49 - 64) / 3.f;
}
//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//{
//    return [self.sortSectionArr objectAtIndex:section];
//}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sortSectionArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger cont = [[self.toDayDic objectForKey:[self.sortSectionArr objectAtIndex:section]] count];
    if (cont > 5) {
        return 6;
    }
    return cont;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellStr = @"cell";
    static NSString *cellMore = @"cellMore";
    
    // 防止crash
    if (self.sortSectionArr.count <= 0) {
        static NSString *cellStr = @"cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        if (nil == cell) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellStr] autorelease];
        }
        cell.textLabel.text = @"程序出错啦~";
        return  cell;
    }
    
    NSString *key = [self.sortSectionArr objectAtIndex:indexPath.section];
    NSMutableArray *arr = [self.toDayDic objectForKey:key];
    TodayHomeModel *toDayMod = [arr objectAtIndex:indexPath.row];
 
    
    if (indexPath.row > 4) {

        TodayHomeMoreCell *cell = [tableView dequeueReusableCellWithIdentifier:cellMore];
        cell.backgroundColor = [UIColor clearColor];
        
        [cell setTimeLabelWithString:[NSString stringWithFormat:@"%02d:%02d", [key intValue], 0]];
        return cell;
    }
    
    
    TodayHomeCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
    cell.toDayMod = toDayMod;
    
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 选中时有置灰效果, 离开时消失选中效果
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    [self.delegate navigationViewWithIsHidden:YES];
    
    if (indexPath.row > 4) {
        NSString *key = [self.sortSectionArr objectAtIndex:indexPath.section];
        
        ToDaySubViewController *toDaySubVC = [[ToDaySubViewController alloc] init];
        toDaySubVC.time = [NSString stringWithFormat:@"%02d:%02d", [key intValue], 0];
        
        // 隐藏
        toDaySubVC.hidesBottomBarWhenPushed = YES;
        toDaySubVC.subArr = [NSMutableArray arrayWithArray:[self.toDayDic objectForKey:key]];
        [self.navigationController pushViewController:toDaySubVC animated:YES];
        [toDaySubVC release];
        
        return;
    }
    
    
    NSString *key = [self.sortSectionArr objectAtIndex:indexPath.section];
    NSMutableArray *arr = [self.toDayDic objectForKey:key];
    TodayHomeModel *toDayMod = [arr objectAtIndex:indexPath.row];

    
    
    ActivitieDetailsViewController *activitieVC = [[ActivitieDetailsViewController alloc] init];
    // 隐藏
    activitieVC.hidesBottomBarWhenPushed = YES;
    activitieVC.activityId = toDayMod.toDayId;
    activitieVC.activityTitle = toDayMod.title;
    
    [self.navigationController pushViewController:activitieVC animated:YES];
    [activitieVC release];
}


#pragma mark - 获取数据
- (void)getUpdate
{
    
    // 让菊花旋转起来
    MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [hub show:YES];
    hub.labelText = @"努力加载中...";
    
    NSString *cityid = [[NSUserDefaults standardUserDefaults] objectForKey:@"cityid"];
    NSString *url = [NSString stringWithFormat:@"http://wanapi.damai.cn/today.json?cateid=0&cityid=%@&day=&source=10344&version=20001", cityid];
    
    [AppTools getAFNet:url block:^(id result) {

        [self.toDayDic removeAllObjects];
        [self.sortSectionArr removeAllObjects];
        
        NSMutableArray *bigArr = [result objectForKey:@"data"];
        
        if (0 == bigArr.count) {
            //结束下拉上拉刷新
            //结束下拉上拉刷新
            [self.myTableV.header endRefreshing];
            [self.myTableV.footer endRefreshing];
            [hub hide:YES];
            [self.myTableV reloadData];
            return;
            
        }
        
        for (NSMutableDictionary *dic in bigArr) {
            NSMutableArray *arr = [NSMutableArray array];
            
            for (NSMutableDictionary *dicTemp in [dic objectForKey:@"list"]) {
                TodayHomeModel *toDayMod = [TodayHomeModel modelWithDictionary:dicTemp];
                [arr addObject:toDayMod];
            }
            [self.toDayDic setObject:arr forKey:[NSString stringWithFormat:@"%@", [dic objectForKey:@"date"]]];
        }

        // 数据解析完毕
        self.sortSectionArr = [NSMutableArray arrayWithArray:self.toDayDic.allKeys];
       
        [AppTools compareSumWithArray:self.sortSectionArr];
        
//        NSLog(@"----%ld", self.sortSectionArr.count);
        
        //结束下拉上拉刷新
        [self.myTableV.header endRefreshing];
        [self.myTableV.footer endRefreshing];
        [hub hide:YES];
        [self.myTableV reloadData];
        
    } errorBlock:^(NSError *error) {
        
        [self NetworkError:^{
        }];
        
        //结束下拉上拉刷新
        [self.myTableV.header endRefreshing];
        [self.myTableV.footer endRefreshing];
        [hub hide:YES];
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
